//
//  UrlRequest.m
//  eventApp
//
//  Created by Zhou Shaolin on 11/18/10.
//  Copyright 2010 Microstrategy. All rights reserved.
//

#import "UrlRequest.h"
#import "UserAccount.h"
#import "Utility.h"  
#import "NSData (MBBase64).h"
#import "MacAddress.h"
@implementation UrlRequest
@synthesize receivedData;
@synthesize delegate;
@synthesize callback;
@synthesize errorCallback;
@synthesize resultToken;


-(id) initWithDelegate:(id)requestDelegate requestSelector:(SEL)requestSelector errorSelector:(SEL)errorSelector
{
    if (self = [super init]) {
        self.delegate = requestDelegate;
        self.callback = requestSelector;
        self.errorCallback = errorSelector;
    }  
    return self;
}

-(void)login:(NSString*)userName pwd:(NSString*)password{
   NSString* sqlText = [NSString stringWithFormat:@"SELECT USER_ID,USER_NAME FROM TUSER WHERE USER_PWD = '%@' and USER_ACTIVE='Y' AND (USER_NAME = '%@' or USER_CODE='%@')", password, userName, userName];
    [self encodeRequest:sqlText];
}
-(void) savePhotoRemark:(NSString*) file_id andContent:(NSString*) content{
    NSString* sqlText = [NSString stringWithFormat:@"update TFILE_LIB set FLIB_NAME='%@' where FLIB_ID='%@'",content,file_id];
    [self encodeRequest:sqlText];
}

-(void)tfFileList{
    NSUserDefaults *userdefault=[NSUserDefaults standardUserDefaults];
    NSString* sqlText = [NSString stringWithFormat:@"select FLIB_ID,FLIB_DESCRIPTION,FLIB_MODEL_NO,FLIB_REMARK,FLIB_CREAT_USER,FLIB_CREAT_TIME,FLIB_NAME from TFILE_LIB where FLIB_CREAT_USER ='%@' order by FLIB_CREAT_TIME desc", [userdefault objectForKey:@"USER_ID"]];
    [self encodeRequest:sqlText];
    //NSLog(@"%@",sqlText);
}

-(void)requestToCheckList:(int) status andKeyWords:(NSString *)keywords{
    NSUserDefaults *userdefault=[NSUserDefaults standardUserDefaults];
    NSArray *array=[[userdefault objectForKey:@"USERH_HEADSHIP"] componentsSeparatedByString:@","];
    NSString *consqlstr=@"";
    for (NSString *item  in array) {
        if (item.length>0) {
            if (consqlstr.length<1) {
                consqlstr=[[@"TASK_HEADSHIP like '%" stringByAppendingString:item] stringByAppendingString:@"%'"];
            }else {
                consqlstr=[[[consqlstr  stringByAppendingString:@" or TASK_HEADSHIP like '%"] stringByAppendingString:item] stringByAppendingString:@"%'"];
            }
        }
    }
    if (consqlstr.length>0) {
        consqlstr=[consqlstr stringByAppendingString:@"  or "];
    }
    NSString  *userStr=[userdefault  objectForKey:@"USER_ID"];
    NSString* sqlText ;
    if (status==0) {
        sqlText=[NSString stringWithFormat:@"select  top (20) BILL_NO as 单号,bill_template_name as 单据类型,bill_remark as 事由,bill_department_name as 部门,bill_project_name as 项目,bill_user_name as 申请人,BILL_SUBMIT_DATETIME as 提单时间,BILL_AMOUNT as 金额,bill_flag_name as 单据状态,BILL_ID as BILL_ID,task_id as TASK_ID,BILL_AUDIT_TYPE_NAME as 审批类型 from  vbill_task where bill_flag not in ('cancel','no') and task_type  not in ('c')   and task_status = 'n'   and  (%@   task_user like '%@') order by bill_no desc",consqlstr,userStr];
    }else{
        
        if ([keywords isEqualToString:@""]) {
            sqlText=[NSString stringWithFormat:@"select  top (20) BILL_NO as 单号,bill_template_name as 单据类型,bill_remark as 事由,bill_department_name as 部门,bill_project_name as 项目,bill_user_name as 申请人,BILL_SUBMIT_DATETIME as 提单时间,BILL_AMOUNT as 金额,bill_flag_name as 单据状态,BILL_ID as BILL_ID,task_id as TASK_ID,BILL_AUDIT_TYPE_NAME as 审批类型 from  vbill_task where bill_flag not in ('cancel','no') and task_type  not in ('c')    and  task_status  not in ('n')   and  (%@   task_user like '%@') order by bill_no desc",consqlstr,userStr];
        }else{
            
            NSString *keywordStr=[[@"%" stringByAppendingString:keywords] stringByAppendingString:@"%"];
            
            sqlText=[NSString stringWithFormat:@"select  top (20) BILL_NO as 单号,bill_template_name as 单据类型,bill_remark as 事由,bill_department_name as 部门,bill_project_name as 项目,bill_user_name as 申请人,BILL_SUBMIT_DATETIME as 提单时间,BILL_AMOUNT as 金额,bill_flag_name as 单据状态,BILL_ID as BILL_ID,task_id as TASK_ID,BILL_AUDIT_TYPE_NAME as 审批类型 from  vbill_task where bill_flag not in ('cancel','no') and task_type  not in ('c')    and  task_status  not in ('n')   and  (%@   task_user like '%@') and (BILL_NO like '%@' or bill_remark  like '%@' or bill_user_name  like '%@') order by bill_no desc",consqlstr,userStr,keywordStr,keywordStr,keywordStr];
        }
        
    }
    [self encodeRequest:sqlText];
    //NSLog(@"%@",sqlText);
}

-(void) requestToHeadShip:(NSString *) user_Id{
    NSString* sqlText = [NSString stringWithFormat:@"SELECT USERH_HEADSHIP FROM TUSER_HEADSHIP WHERE (USERH_USER = '%@')",user_Id];
    [self encodeRequest:sqlText];
}
-(void) saveImageData{
    NSUserDefaults *userdefault=[NSUserDefaults standardUserDefaults];
    char* macAddressString = (char*)malloc(18);
    NSString *macAddress = [[NSString alloc] initWithCString:[MacAddress getMacAddress:macAddressString andIfName:"en0"] encoding:NSMacOSRomanStringEncoding];
    NSString* sqlText = [NSString stringWithFormat:@"Insert into TFILE_LIB ( FLIB_ID,FLIB_DESCRIPTION,FLIB_MODEL_NO,FLIB_REMARK,FLIB_CREAT_USER,FLIB_CREAT_TIME,FLIB_RECEIVE_NO) values                         ('%@','%@','%@','%@','%@','%@','%@')",
                         [userdefault objectForKey:@"file_id"],
                         [userdefault objectForKey:@"imagePath"],macAddress,
                         [userdefault objectForKey:@"gpsAddress"],
                         [userdefault objectForKey:@"USER_ID"],
                         [userdefault objectForKey:@"createDate"],
                         [userdefault objectForKey:@"gps"]
                         ];
    //NSLog(@"%@",sqlText);
    [self encodeRequest:sqlText];
}

-(void) requestToLiuChengShePi:(NSString *) bill_no{
    NSString* sqlText = [NSString stringWithFormat:@"select  USER_NAME as 审批人,HEADSHIP_NAME as 审批人职务 ,TASK_RESULT 审批意见,TASK_LAST_DATETIME 审批时间,SDD_NAME as 任务类型  from VTASK_RESULT_LIST where TASK_HEADSHIP is not null and bill_no='%@' order by TASK_LAST_DATETIME",bill_no];
    [self encodeRequest:sqlText];
}

-(void) saveShenheToserve:(NSDictionary *) param{
    NSUserDefaults *userDefault=[NSUserDefaults standardUserDefaults];
    NSString *user_id=[userDefault  objectForKey:@"USER_ID"];
    
   // NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    //[formatter setDateFormat:@"YYYY-MM-dd"];
    //NSString *dateStr = [formatter stringFromDate:[NSDate  date]];
   // NSString* sqlText = [NSString stringWithFormat:@"update TWFE_TASK set TASK_FLAG=%d,TASK_STATUS='%@',TASK_RESULT='%@'  where TASK_ID='%@'",[[param  objectForKey:@"TASK_FLAG"] intValue],[param  objectForKey:@"TASK_STATUS"],[param  objectForKey:@"TASK_RESULT"],[param  objectForKey:@"TASK_ID"]];
    NSString* sqlText = [NSString stringWithFormat:@"update TWFE_TASK set TASK_LAST_DATETIME=getdate(),TASK_STATUS='%@',TASK_RESULT='%@',TASK_LAST_USER='%@' where TASK_ID='%@'",[param  objectForKey:@"TASK_STATUS"],[param  objectForKey:@"TASK_RESULT"],user_id,[param  objectForKey:@"TASK_ID"]];
    [self encodeRequest:sqlText];
   // [formatter release];
    // NSLog(@"%@",sqlText);
}

-(void) encodeRequest:(NSString*) sqlText{
//封装soap请求消息
	/*NSString *soapMessage = [NSString stringWithFormat:
							 @"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
                             "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
                             "<soap:Body>\n"
                             "<GetDataSetSql xmlns=\"http://tempuri.org/\">\n"
                             "<sysParams>\n"];*/
    NSString *soapMessage = [NSString stringWithFormat:
							 @"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
                             "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
                             "<soap:Body>\n"
                             "<GetDataSetSql xmlns=\"http://tempuri.org/\">\n"];
    /*NSArray* sysParams = [NSArray arrayWithObjects:    
                          @"S0001", @"admin", @"server=192.168.1.101;Enlist=False;uid=sa;pwd=Sa123456;database=HTDC", @"", @"GB", @"HS_PUBLIC", @"1", @"http://192.168.1.101:809/", @"1", nil];
    

    for (NSString* item in sysParams) {
        soapMessage = [soapMessage stringByAppendingFormat:@"<string>%@</string>\n", item];
    }
    soapMessage = [soapMessage stringByAppendingFormat:@"</sysParams>\n"];*/
    NSUserDefaults *userdefault=[NSUserDefaults  standardUserDefaults];
     soapMessage = [soapMessage stringByAppendingFormat:@"%@", [userdefault  objectForKey:@"sysParams"]];
    soapMessage = [soapMessage stringByAppendingFormat:@"<sql>%@</sql>\n"
                   "</GetDataSetSql>\n"
                   "</soap:Body>\n"
                   "</soap:Envelope>\n",sqlText];
	//NSLog(soapMessage);
	//请求发送到的路径
   // self.resultToken = @"GetDataSetSqlResult";
    NSString *url=[[[NSUserDefaults standardUserDefaults] objectForKey:@"kServiceURL"] stringByAppendingPathComponent:@"WebService.asmx"];
    theRequest = [NSMutableURLRequest requestWithURL:[NSURL  URLWithString:url]];
	NSString *msgLength = [NSString stringWithFormat:@"%d", [soapMessage length]];
	
	//以下对请求信息添加属性前四句是必有的，第五句是soap信息。
	[theRequest addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    
    NSString* serviceFunc = [NSString stringWithFormat:@"http://tempuri.org/%@", @"GetDataSetSql"];
	[theRequest addValue: serviceFunc forHTTPHeaderField:@"SOAPAction"];
	
	[theRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];
	[theRequest setHTTPMethod:@"POST"];
	[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
    [self request:[NSURL  URLWithString:url]];
    
}
-(void) postFileWithRequest:(NSData*) data imagePath:(NSString*)imagepath{
    NSString *soapMessage = [NSString stringWithFormat:
							 @"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
                             "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
                             "<soap:Body>\n"
                             "<UploadFile xmlns=\"http://tempuri.org/\">\n"];
   soapMessage = [soapMessage stringByAppendingFormat:@"<VirtualPath>%@</VirtualPath>\n",@"root"];
    soapMessage = [soapMessage stringByAppendingFormat:@"<Name>%@</Name>\n",imagepath];
    soapMessage = [soapMessage stringByAppendingFormat:@"<Content>%@</Content>\n",[data base64Encoding]];
            soapMessage = [soapMessage stringByAppendingFormat:@"<BillNo>%@</BillNo>\n",@""];
    soapMessage = [soapMessage stringByAppendingFormat:@
                   "</UploadFile>\n"
                   "</soap:Body>\n"
                   "</soap:Envelope>\n"];
    NSString *url=[[[NSUserDefaults standardUserDefaults] objectForKey:@"kServiceURL"] stringByAppendingPathComponent:@"WebService.asmx"];
    theRequest = [NSMutableURLRequest requestWithURL:[NSURL  URLWithString:url]];
	NSString *msgLength = [NSString stringWithFormat:@"%d", [soapMessage length]];
	
	//以下对请求信息添加属性前四句是必有的，第五句是soap信息。
	[theRequest addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    
    NSString* serviceFunc = [NSString stringWithFormat:@"http://tempuri.org/%@", @"UploadFile"];
	[theRequest addValue: serviceFunc forHTTPHeaderField:@"SOAPAction"];
	
	[theRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];
	[theRequest setHTTPMethod:@"POST"];
	[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
    [self request:[NSURL  URLWithString:url]];
    
}


-(void)request:(NSURL *) url {
	[theRequest setTimeoutInterval:100];
	theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
	
	if (theConnection) {
		receivedData=[[NSMutableData data] retain];
	} else {
		// inform the user that the download could not be made
	}
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
     [receivedData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
	  [receivedData appendData:data];
}

- (void)connection:(NSURLConnection *)connection
  didFailWithError:(NSError *)error{
	if(errorCallback) {
		[delegate performSelector:errorCallback withObject:error];
	}
	
	[self releaseResources];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
	NSString* receivedString = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
    
	if(delegate && callback) {
		if([delegate respondsToSelector:self.callback]) {
			[delegate performSelector:self.callback withObject:receivedString];
		} else {
			//NSLog(@"No response from delegate");
		}
	}
	
	// release the connection, and the data object
	[self releaseResources];
}


-(void) releaseResources{
	[theConnection release];
	theConnection = nil;
	[receivedData release];
	receivedData = nil;
}

-(void) dealloc {
	[delegate release];
	[receivedData release];
    //[resultToken release];
	[super dealloc];
}

@end
